import {getPictureList} from "./src/picture-list";
import {nodeHTTP} from "./src/NodeEnhance/http";
import nodeURL from "url";
import {nodeFileSys, readFile} from "./src/NodeEnhance/fileSys";
import {joinPath, nodePath} from "./src/NodeEnhance/path";
import {LOCAL_ROOT_DIR} from "./src/app-vars";

function responseList(res: nodeHTTP.ServerResponse) {
    getPictureList().then((result) => {
        res.writeHead(200, {
            "Content-Type": "application/json",
        });
        res.write(JSON.stringify(result));
        res.end();
    }).catch((err) => {
        console.error(err);
    });
}

function giveFEImg(req: nodeHTTP.IncomingMessage, res: nodeHTTP.ServerResponse) {
    if (req.url) {
        const urlParse = nodeURL.parse(req.url);
        const picURL = decodeURIComponent(urlParse.pathname || "").replace(/^\/getImg\//, "");
        console.log("request url", req.url);
        if (picURL) {
            const localFile = joinPath(LOCAL_ROOT_DIR, picURL);
            if (nodeFileSys.existsSync(localFile)) {
                readFile(localFile, "binary").then((data) => {
                    res.writeHead(200, {
                        "Content-Type": "image/jpeg",
                    });
                    res.write(data, "binary");
                    res.end();
                }).catch((err) => {
                    console.error(err);
                    process.exit(2);
                });
                return ;
            }
        }
    }
    res.writeHead(404, {
        "Content-Type": "text/plain",
    });
    res.write("not found [" + req.url);
    res.end();
}

function getMIMEByExt(type: string) {
    switch (type) {
        case ".css":
            return "text/css";
        case ".js":
            return "text/javascript";
        case ".html":
            return "text/html";
        default:
            return "text/plain";
    }
}

function giveFESrc(req: nodeHTTP.IncomingMessage, res: nodeHTTP.ServerResponse) {
    if (!req.url) {
        req.url = "/";
    }
    const urlParse = nodeURL.parse(req.url);
    let localPath = urlParse.pathname;
    if (!localPath || localPath === "/") {
        localPath = "/index.html";
    }
    const absLocalPath = joinPath(__dirname, "./fe/", localPath);
    const pathParsed = nodePath.parse(absLocalPath);
    console.log("get src from " + absLocalPath, urlParse);
    if (nodeFileSys.existsSync(absLocalPath)) {
        readFile(absLocalPath, "utf8").then((data) => {
            res.writeHead(200, {
                "Content-Type": getMIMEByExt(pathParsed.ext),
            });
            res.write(data, "utf8");
            res.end();
        }).catch((err) => {
            console.error(err);
            process.exit(2);
        });
        return ;
    }
    res.writeHead(404, {
        "Content-Type": "text/plain",
    });
    res.write("not found [" + req.url);
    res.end();
}

const server = nodeHTTP.createServer((req, res) => {
    if (req.url === "/getList") {
        responseList(res);
        return ;
    }
    if (req.url && req.url.match(/^\/getImg/)) {
        giveFEImg(req, res);
        return ;
    }
    giveFESrc(req, res);
});

server.on("error", (err) => {
    console.error(err);
});

server.listen(8080, "0.0.0.0", () => {
    console.log("open at: http://127.0.0.1:8080");
});
